<?php
namespace App\Helpers\Adapay;
class HfAdaPay
{
    public $appid = 'app_20bfa8b6-4893-4df5-ba8e-a13ed182c563';

    public function __construct(){
        $path = app_path('Helpers');
        require_once $path . '/Adapay/AdapaySdk/init.php';

        \AdaPay\AdaPay::init(self::getConfig(), "live", true);
    }

    public static function getConfig(){
        $jsonPath = [
            "api_key_live" => "api_live_48efc884-13f8-4691-bef6-d747615143fa",
            "api_key_test" => "api_test_cf703b6d-5035-4482-ba36-acf2d23421ec",
            "rsa_public_key" => "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwN6xgd6Ad8v2hIIsQVnbt8a3JituR8o4Tc3B5WlcFR55bz4OMqrG/356Ur3cPbc2Fe8ArNd/0gZbC9q56Eb16JTkVNA/fye4SXznWxdyBPR7+guuJZHc/VW2fKH2lfZ2P3Tt0QkKZZoawYOGSMdIvO+WqK44updyax0ikK6JlNQIDAQAB",
            "rsa_private_key" => "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAK62jul2ju73LL1/gK42H9QcDcFrJTNoese7E170NSpjjvgolJJCqurryONAz6aQhhApeqox92VWiUqxRLqGGRRM+9gC1Azy4eZ2QqhTmT81BH28cdGpQ/+J6sIboKXOsrflzy5hfqGciQ2lGNEcr5hS9CMvshJ07maLTs71t9HZAgMBAAECgYBqAMO27MMORBP2Ka0WhipLlHXYG70ncsXD90JqgzrarCsrb9us3hw7irGJCGK0yc09cx1EtCpJZvbHxcRQc1o1DnAdMf+E42jrn4rv5uelC00V2UxYJ3O+qyD/WQ8q720C2YBFojIPZCrmsr6CuOJ4ALOaDuccq06M2lqLdApu7QJBAPXbS2+Xq3gfhVEvNEY98a+VKJ4339ziH8/IdXeVPvuL82cVW6BWC85T3cirkcwpHd7G4LYmeP4yzBsim2m9+nMCQQC169ryKwzONJDzlrsPO6qFReo5GrdzZRlCWRW+C33ofoYu7+jFHRBFO/yLfCr+Q4311lBlsgZrl+pk5Zu7RXODAkBfPqZ5w8s0zRlLuzrIH4U63VEQAltiaeOjDmibfCEbODuCat7FPbBzLUBVVko0SpV80ZUKW9sxtyIlPQHyNBwLAkBFkkA2Ep6gEVxJu6An8DKDKzyqv/veRpCFXhpBhpWNHy3jr13+W+IICCvJkB/FA0K7/Ezcx1tLNFqwYVrQIHxPAkB+r9Vas4SB6224vwy7CwnfZtREn1qHxRtEWDjJP+ZW91CEWDirSAdweHNFvvVbOpXiKvX/9OObB7yzqmI7qWxG"
        ];
        return $jsonPath;
    }

    public function createUser($memberId , $nickname , $cardId , $cardName , $certId , $mobile){
        $payment = new \AdaPaySdk\Member();
        $payment->create([
            'app_id' => $this->appid,
            'member_id' => $memberId ,
            'nickname' => $nickname ,
        ]);
        if ($payment->isError()){
            if ($payment->result['error_code'] == 'member_id_exists'){
                list($status , $msg) = $this->addSettleAccount($memberId , $cardId , $cardName , $certId , $mobile);
                if ($status){
                    return [true , $msg];
                }
                return [false , $msg];
            }
            self::addLogs('createUser' , $payment->result , 'sync_hf');
            return [false , $payment->result['error_msg']];
        }else{
            self::addLogs('createUser' , $payment->result , 'sync_hf');
            $result = $payment->result;
            if ($result['status'] == 'succeeded'){
                // 成功
                list($status , $msg) = $this->addSettleAccount($memberId , $cardId , $cardName , $certId , $mobile);
                if ($status){
                    return [true , $msg];
                }
                return [false , $msg];
            }
        }
        return [false , '未知错误'];
    }

    public function updateUser($memberId , $settleId , $cardId , $cardName , $certId , $mobile , $nickname = ''){
        $payment = new \AdaPaySdk\Member();
        $payment->update([
            'app_id' => $this->appid,
            'member_id' => $memberId ,
            'nickname' => $nickname ,
        ]);
        if ($payment->isError()){
            self::addLogs('updateUser' , $payment->result , 'sync_hf');
            return [false , $payment->result['error_msg']];
        }else{
            self::addLogs('updateUser' , $payment->result , 'sync_hf');
            $result = $payment->result;
            if ($result['status'] == 'succeeded'){
                // 成功
                list($status , $msg) = $this->deleteSettleAccount($memberId , $settleId);
                if ($status){
                    list($status , $msg) = $this->addSettleAccount($memberId , $cardId , $cardName , $certId , $mobile);
                    if ($status){
                        return [true , $msg];
                    }
                }
                return [false , $msg];
            }
        }
        return [false , '未知错误'];
    }

    /**
     * 添加结算账户
     * @param $memberId
     * @param $cardId
     * @param $cardName
     * @param $certId
     * @param $mobile
     * @return array
     * @author <amcolin@126.com>
     * @time 2023/5/29 21:59
     */
    public function addSettleAccount($memberId , $cardId , $cardName , $certId , $mobile){
        $payment = new \AdaPaySdk\SettleAccount();
        $payment->create([
            'app_id' => $this->appid,
            'member_id' => $memberId ,
            'channel'=> 'bank_account',
            'account_info'=> [
                'card_id' => $cardId, //Y 银行卡号
                'card_name' => $cardName, //Y 银行卡对应的户名
                'cert_id' => $certId, //N 证件号，银行账户类型为对私时，必填
                'cert_type' => '00', //N 证件类型，仅支持：00-身份证，银行账户类型为对私时，必填
                'tel_no' => $mobile,//Y 手机号
//                'bank_code' => '03060000', //N 银行编码，详见附录 银行代码，银行账户类型对公时，必填
//                'bank_name' => '建hua', //N 开户银行名称
                'bank_acct_type' => 2, //Y 银行账户类型：1-对公；2-对私
//                'prov_code' => '0031', //N 银行账户开户银行所在省份编码 （省市编码），银行账户类型为对公时，必填
//                'area_code' => '3100',//N 银行账户开户银行所在地区编码（省市编码），银行账户类型为对公时，必填
            ]
        ]);
        if ($payment->isError()){
            self::addLogs('addSettleAccount' , $payment->result , 'sync_hf');
            return [false , $payment->result['error_msg']];
        } else{
            self::addLogs('addSettleAccount' , $payment->result , 'sync_hf');
            return [true , $payment->result['id']];
        }
    }

    /**
     * 删除结算账户
     * @param $memberId
     * @param $settleAccountId
     * @return array
     * @author <amcolin@126.com>
     * @time 2023/5/29 21:59
     */
    public function deleteSettleAccount($memberId , $settleAccountId){
        $payment = new \AdaPaySdk\SettleAccount();
        $account_params = array(
            'app_id'=> $this->appid,
            'member_id'=> $memberId,
            'settle_account_id'=> $settleAccountId
        );
        # 查询结算账户
        $payment->delete($account_params);
        if ($payment->isError()){
            self::addLogs('deleteSettleAccount' , $payment->result , 'sync_hf');
            // array(5) { ["status"]=> string(6) "failed" ["error_type"]=> string(21) "invalid_request_error" ["error_code"]=> string(18) "account_not_exists" ["error_msg"]=> string(21) "结算账户不存在" ["prod_mode"]=> string(4) "true" }
            if ($payment->result['error_code'] == 'account_not_exists'){
                return [true , ''];
            }
            return [false , $payment->result['error_msg']];
        }else{
            self::addLogs('deleteSettleAccount' , $payment->result , 'sync_hf');
            // array(3) { ["id"]=> string(16) "0483226062825344" ["status"]=> string(9) "succeeded" ["prod_mode"]=> string(4) "true" }
            return [true , ''];
        }
    }

    public function selectOrder($paymentId = ''){
        $payment = new \AdaPaySdk\Payment();
        # 请求参数
        $payment_params = array(
            'app_id'=> $this->appid,
            "payment_id"=> $paymentId,
        );
        $payment->queryList($payment_params);
        if ($payment->isError()){
            //失败处理
            self::addLogs('selectOrder' , $payment->result , 'sync_hf');
            return [false , $payment->result['error_msg']];
        } else {
            self::addLogs('selectOrder' , $payment->result , 'sync_hf');
            //成功处理
            if (isset($payment->result['payments'])){
                $payments = $payment->result['payments'][0];
                if ($payments['status'] == 'succeeded'){
                    return [true , $payments['id']];
                }
            }
        }
        return [false , $payment->result];
    }

    public function sharing($paymentId , $confirm_amt , $members = [] , $orderId = ''){
        # 初始化支付确认对象类
        $payment = new \AdaPaySdk\PaymentConfirm();
        $orderId = $orderId ? $orderId : date("YmdHis").rand(100000, 999999);
        # 支付设置
        $payment_params = array(
            'payment_id'=> $paymentId, // Adapay生成的支付对象id
            'order_no'=> $orderId, // 请求订单号，只能为英文、数字或者下划线的一种或多种组合，保证在app_id下唯一
            'confirm_amt'=> $confirm_amt, // 确认金额，必须大于0，保留两位小数点，如0.10、100.05等。必须小于等于原支付金额-已确认金额-已撤销金额。
            'div_members'=> $members , // 分账对象信息列表，一次请求最多仅支持7个分账方。json对象 形式，详见 分账对象信息列表
            'fee_mode' => 'I' , // 手续费收取模式：O-商户手续费账户扣取手续费，I-交易金额中扣取手续费；值为空时，默认值为I；若为O时，分账对象列表中不支持传入手续费承担方
        );
        # 创建支付确认对象
        $payment->create($payment_params);
        # 对支付结果进行处理
        if ($payment->isError()){
            self::addLogs('sharing' , $payment->result , 'sync_hf');
            //失败处理
            return [false , $payment->result['error_msg']];
        } else {
            self::addLogs('sharing' , $payment->result , 'sync_hf');
            //成功处理
            if ($payment->result['status'] == 'succeeded'){
                return [true , $payment->result];
            }
        }
        return [false , '未知错误'];
    }

    public function cancelSharing($payment_confirm_id){
        $request = new \AdaPaySdk\AdaPayCommon();
        $params = [
            'adapay_func_code' => 'payments.confirm.reverse' , // Adapay接口功能号：payments.confirm.reverse
            'payment_confirm_id' => $payment_confirm_id , // Adapay生成的支付确认对象id
            'order_no' => date("YmdHis").rand(100000, 999999) , // 请求订单号，只能为英文、数字或者下划线的一种或多种组合
        ];
        $request->requestAdapay($params);
        if ($request->isError()){
            self::addLogs('cancelSharing' , $request->result , 'sync_hf');
            //失败处理
            return [false , $request->result['error_msg']];
        } else {
            self::addLogs('sharing' , $request->result , 'sync_hf');
            //成功处理
            if ($request->result['status'] == 'succeeded'){
                return [true , $request->result];
            }
        }
        return [false , '未知错误'];
    }

    public function selectBalance($memberId , $settleAccountId){
        $wallet = new \AdaPaySdk\SettleAccount();
        $account_params = array(
            # 应用ID
            'app_id'=> $this->appid,
            # 用户ID
            'member_id'=> $memberId,
            // 由Adapay生成的结算账户对象id，若查询商户本身时，可以为空
            'settle_account_id'=> $settleAccountId
        );
        # 查询账户余额
        $wallet->balance($account_params);
        # 对支付结果进行处理
        if ($wallet->isError()){
            //失败处理
            return [false , $wallet->result['error_msg']];
        } else {
            //成功处理
            if ($wallet->result['status'] == 'succeeded'){
                return [true , [
                    'avl_balance' => $wallet->result['avl_balance'] ,
                    'frz_balance' => $wallet->result['frz_balance'] ,
                    'last_avl_balance' => $wallet->result['last_avl_balance'] ,
                    'acct_balance' => $wallet->result['acct_balance'] ,
                ]];
            }
        }
        return [false , '未知错误'];
    }

    protected static function addLogs($message , $content = [] , $fileName = ''){
        if (is_array($content) && $content){
            $content = ' >> ' . json_encode($content , JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        }else{
            $content = '';
        }
        file_put_contents('./'.$fileName.'.log' , '【'.date('Y-m-d H:i:s').'】' . $message . $content . PHP_EOL , FILE_APPEND);
    }
}
